import React, {useState, useEffect} from 'react';
import {
  Animated,
  Easing,
  View,
  Dimensions,
  Text,
  StyleSheet,
  StatusBar,
} from 'react-native';
import {RNCamera} from 'react-native-camera';
import {Button, ActivityIndicator} from '@ant-design/react-native';

const styles = StyleSheet.create({
  mainContainer: {flex: 1},
  topInfoView: {
    top: 70,
    position: 'absolute',
    width: Dimensions.get('window').width,
    alignItems: 'center',
  },
  camera: {
    flex: 0,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },

  rectangleContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },

  rectangle: {
    borderWidth: 2,
    borderColor: '#00FF00',
    backgroundColor: 'transparent',
  },
  scannedRectangle: {
    backgroundColor: 'antiquewhite',
    width: Dimensions.get('window').width,
  },
  rectangleText: {
    flex: 0,
    color: '#fff',
    marginTop: 10,
  },
  border: {
    flex: 0,
    backgroundColor: '#00FF00',
  },
  circle: {
    marginRight: 10,
    alignItems: 'center',
    justifyContent: 'center',
    width: 28,
    height: 28,
    backgroundColor: '#00ff00',
    borderStyle: 'solid',
    borderRadius: 15,
    paddingBottom: 2,
  },
  exitButton: {
    marginTop: 20,
  },
});

function RnBarcodeScanner({
  topContent,
  onExitScan,
  onBarCodeRead,
  scanProcessing,
  cameraStyle,
  scannedBarcode,
}) {
  const [barcode, setBarcode] = useState(null);
  //const [cameraReady, setCameraReady] = useState(false);
  const [moveAnimate] = useState(new Animated.Value(0));
  const windowHeight = Dimensions.get('window').height;
  const windowWidth = Dimensions.get('window').width;
  const fullscreenStyle = {
    height: windowHeight,
    width: windowWidth,
  };
  const cameraWidth = windowWidth * 0.6;
  const cameraHeight = 270;
  const cameraSizeStyle = {
    height: cameraHeight,
    width: cameraWidth,
  };
  const borderSizeStyle = {
    width: cameraWidth - 20,
    height: 2,
  };

  const startAnimation = () => {
    moveAnimate.setValue(-cameraHeight + 20);
    Animated.timing(moveAnimate, {
      toValue: -2,
      duration: 5000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start(() => startAnimation());
  };
  useEffect(() => {
    StatusBar.setHidden(true);
    startAnimation();
    if (scannedBarcode) {
      setBarcode(scannedBarcode);
    }
    return () => {
      StatusBar.setHidden(false);
    };
  }, []);

  return (
    <View style={[styles.camera, fullscreenStyle, cameraStyle]}>
      <RNCamera
        type={RNCamera.Constants.Type.back}
        flashMode={RNCamera.Constants.FlashMode.off}
        captureAudio={false}
        onBarCodeRead={(args) => {
          if (!barcode && args.data) {
            moveAnimate.stopAnimation();
            setBarcode(args.data);
            onBarCodeRead(args.data);
          }
        }}
        androidCameraPermissionOptions={{
          title: 'Permission to use camera',
          message: 'We need your permission to use your camera',
          buttonPositive: 'Ok',
          buttonNegative: 'Cancel',
        }}>
        {({status}) => {
          if (
            status === RNCamera.Constants.CameraStatus.PENDING_AUTHORIZATION
          ) {
            return <ActivityIndicator text="相机启动中..." />;
            /*} else if (!cameraReady) {
            Toast.fail('无相机权限即将退出扫描', 1, () => {
              onExitScan();
            });
            return null;
*/
          }
          if (scanProcessing) {
            return (
              <View
                style={[styles.rectangleContainer, styles.scannedRectangle]}>
                <View style={styles.topInfoView}>{topContent || null}</View>
                <ActivityIndicator toast size="large" text="处理中..." />
              </View>
            );
          }
          return (
            <View
              style={[
                styles.rectangleContainer,
                fullscreenStyle,
                barcode ? styles.scannedRectangle : undefined,
              ]}>
              <View style={styles.topInfoView}>{topContent || null}</View>
              {!!barcode && <View style={styles.circle} />}
              {!barcode && (
                <>
                  <View style={[styles.rectangle, cameraSizeStyle]} />
                  <Animated.View
                    style={[
                      styles.border,
                      borderSizeStyle,
                      {transform: [{translateY: moveAnimate}]},
                    ]}
                  />
                  <Text style={styles.rectangleText}>
                    将二维码/条码放入框内，开始自动扫描
                  </Text>
                </>
              )}
              {!!barcode && (
                <Button
                  type="ghost"
                  onPress={() => {
                    setBarcode(null);
                  }}
                  style={styles.exitButton}>
                  继续扫描
                </Button>
              )}
              <Button
                type="warning"
                onPress={onExitScan}
                style={styles.exitButton}>
                退出扫描
              </Button>
            </View>
          );
        }}
      </RNCamera>
    </View>
  );
}

export default RnBarcodeScanner;

// https://segmentfault.com/a/1190000014955481
// http://fengtianhe.cn/ReactNative-%E7%BB%84%E4%BB%B6react-native-camera/
// https://enappd.com/blog/react-native-qr-code-scanning-using-react-native-camera/117/  https://github.com/moaazsidat/react-native-qrcode-scanner/blob/master/index.js
// limit scan area https://github.com/react-native-community/react-native-camera/issues/1503 2791  native module https://github.com/react-native-component/react-native-smart-barcode
// https://www.jianshu.com/p/2cef1baf9a6f
//
//  http://barcode.cnaidc.com/html/BCGcode128b.php
